<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class login extends CI_Controller {
	var $data;
	public function __construct()
	{
		parent::__construct();		
		$this->load->library('session');
		$this->load->helper('cookie');
		$this->load->library('fclass');
		$this->load->model('model_login');
		$this->load->model('model_user');
		$this->load->model('model_setting');
		$this->data['title'] = 'Login';
	
		$this->data["system_url"] = "http://login.alta.com.vn/";
		$this->data["system_url_api"] = "http://localhost/ht/hrm/";
	}
	
	public function index()
	{
		$check = $this->session->userdata('login');
		if($check==true){
			redirect(base_url().'dashboard/', 'refresh');
		}else{
			$this->view();
		}		
	}
	
	
	public function view(){
		if(isset($_POST["submit"])||isset($_REQUEST["token"])){	
			$username = $this->input->get_post("username");
			$password = $this->input->get_post("password");
			if(isset($_REQUEST["token"])){
				$result = $this->fclass->getContent($this->data["system_url_api"]."api/login_token?token=".$_REQUEST["token"]."&app_name=AM_SALE_SUPPORT");
				
				
			}else{
				$result = $this->fclass->getContent($this->data["system_url_api"]."api/login?username=".urlencode($username)."&password=".urlencode($password)."&app_name=AM_SALE_SUPPORT");
			}
			
			$this->data["user"]  = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$this->session->userdata('user_token')."&app_name=AM_SALE_SUPPORT");
			//return;
			$json = json_decode($result,true);	
			
			$msg = "ERROR";
			if(isset($json["result"]) && $json["result"] == true){
				$token = $json["token"];
				$expire_date = $json["expire_date"];
				$session = $json["user_info"];
				//print_r($session);
				$this->session->set_userdata('login',$json["result"]);
				$this->session->set_userdata('user_info',$session);
				$this->session->set_userdata('user_token',$token);
				$this->session->set_userdata('expire_date',$expire_date);
				$this->session->set_userdata('uId',$session["user_id"]);
				//$this->session->set_userdata('parentId',$session["parentId"]);
				$room_code = $session["room_code"];
				$user_parent_id = array();
				$user_parent_id[]=$session["user_id"];
				if($session["user_type"]==1){
					$user  = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$token."&app_name=AM_SALE_SUPPORT");
					$us_array = json_decode($user,true);					
					if($us_array["result"]==true){
					foreach($us_array["users"] as $val){
							if(strlen($val["room_code"])>=strlen($room_code)){
								if(substr($val["room_code"],0,strlen($room_code))==$room_code&&$val["user_id"]!=$session["user_id"]){
									$user_parent_id[] = $val["user_id"];
								}
							}
						}
					}else{
						if(isset($json["result_type"])&&$json["result_type"]==0){
							redirect($this->data["system_url"]."?redirect=http://crm.altamedia.vn&out", 'refresh');	
						}else{
							redirect($this->data["system_url"], 'refresh');
						}
					}
				}
				//print_r($user_parent_id);
				
				$this->session->set_userdata('test',json_encode(array('sssss')));
				
				$this->session->set_userdata('parentId',$user_parent_id);
				if($this->input->get_post("rederect")!=""){
					redirect($this->input->get_post("rederect"), 'refresh');
				}else{
					redirect(base_url().'dashboard/', 'refresh');
					}
				
			}else{
			redirect(base_url().'dashboard/', 'refresh');
			}
			
			if(isset($json["msg"])){
				$msg = $json["msg"];
			}
			
			$this->data["msg"] = $msg;	

		}else{
			redirect($this->data["system_url"], 'refresh');
		}
	$this->load->view('login', $this->data);

	}
}


/*
	public function view(){

		if(!isset($_GET["token"])||trim($_GET["token"])==""){
			redirect($this->data["system_url"].'?redirect='.base_url()."?&out", 'refresh');
		}


	//	if(isset($_POST["submit"])){
		//	$username=trim($_POST["username"]);
		//	$password=trim($_POST["password"]);

		//	if($username==""){
		//		$this->data['msg']="Username not null";
		//	}else if($password==""){
		//		$this->data['msg']="Password not null";
		//	}else{
			//	$this->data['data'] = $this->model_login->select(array('username'=>$username));		
			//	if(count($this->data['data'])>0){
				//	if($this->data['data']["uPassword"]==md5($password)){
						//echo $this->data["system_url"]."api.php?mod=check_token&token=".$_GET["token"]."</br>";
						$result = $this->fclass->getContent($this->data["system_url"]."api.php?mod=check_token&token=".$_GET["token"]);
						$array = json_decode($result,true);
						$value = $array["user_info"];
						//print_r($val);
						if($array["result"]==false){
							redirect($this->data["system_url"].'?redirect='.base_url()."&out", 'refresh');
							exit();
						}



						$setting = $this->model_setting->get_setting();

						// GET PARRENT USER
						if($value["user_type"]==1){
							$result = $this->model_user->selectParent(array("rId"=>$value["department_id"],"uStatus"=>1));
						}else if($this->fclass->check_permission('special','is_accounting',json_decode($value["permission"],true),json_decode($value["permission_base"],true))){
							$result = $this->model_user->selectParent(array("uStatus"=>1));
						}else{
							$result = $this->model_user->selectParent(array("rId"=>$value["department_id"].".","uStatus"=>1));
						}

						$array="";
						if(count($result)>0){
							foreach($result as $val){
								$array.=$val["uId"]."|";
							}	
						}
						//print_r($array);
						// END PARRENT USER

						$permission_apps =  "";
						if(isset($value["permission_apps"]["sale_support"])){
							$permission_apps = $value["permission_apps"]["sale_support"] ;
						}

						$session = array(
							'login'  => TRUE,
							'username'     => $value["username"],
							'fullname' 	=> $value["full_name"],
							'department' => $value["department_name"],
							'permissions' =>	$value["permission"],
							'permissions2' => json_decode($value["permission"],true),
							'permissions_base' => json_decode($value["permission_base"],true),
							'permission_apps' => $permission_apps,							
							'rId' => $value["department_id"],
							'uId' =>  $value["user_id"],
							'uType' => $value["user_type"],
							'parentId' => $array
							);
							//print_r($session);
						$this->session->set_userdata($session);

							if($this->fclass->check_permission('special','is_ceo',$this->session->userdata('permissions2'),$this->session->userdata('permissions_base')) ||
							$this->fclass->check_permission('special','is_accounting',$this->session->userdata('permissions2'),$this->session->userdata('permissions_base'))||
							$this->fclass->check_permission('special','is_sale',$this->session->userdata('permissions2'),$this->session->userdata('permissions_base'))){
				
					//	$cookie = array(
					//			'userId'   => $this->data['data']['uId'],
					//			'userName'    => $username,
					//			'userPass' => md5($password)
					//			);

					//	 $this->input->set_cookie($cookie);
					



		
						//print_r($this->session->all_userdata());
					//setcookie("userId", $this->data['data']['uId']);
					//setcookie("userName", $username);
					//setcookie("userPass", md5($password));
					

					redirect(base_url().'dashboard/', 'refresh');
					return 1;
				}else{
					$this->data['msg']="Session Clear";
					$this->session->sess_destroy();
					redirect($this->data["system_url"].'?redirect='.base_url()."&msg=".urlencode("Bạn không có quyền truy cập vào trang SaleSupport")."&out", 'refresh');
				}
		//	}else{
			//	$this->data['msg']="Password Wrong";
			//}
	//	}else{
		//	$this->data['msg']="Username does't exists";
	//	}
	//}



//$this->load->view('login', $this->data);
}
}

*/